package cn.wsalix.shop.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.admin.BaseUser;
import cn.anlaser.service.impl.CommonServiceImpl;
import cn.anlaser.status.FlagEnum;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.shop.entity.Product;
import cn.wsalix.shop.entity.ShopCart;
import cn.wsalix.shop.form.ShopCartForm;
import cn.wsalix.shop.repository.ShopCartRepository;
import cn.wsalix.shop.service.ProductService;
import cn.wsalix.shop.service.ShopCartService;

@Service("ShopCartService")
public class ShopCartServiceImpl extends
		CommonServiceImpl<ShopCartForm, ShopCartRepository, ShopCart> implements
		ShopCartService {
	@Autowired
	private ShopCartRepository shopCartRepository;
	@Autowired
	private ProductService productService;

	@Override
	public String module() {
		return "/shop/shop_cart";
	}

	@Override
	public ShopCartRepository getRepository() {
		return shopCartRepository;
	}

	@Override
	public Class<ShopCart> getEntityClazz() {
		return ShopCart.class;
	}

	@Transactional
	@Override
	public ShopCart getNew(ShopCartForm form) {
		Product product = productService.findById(form.getProductId());
		ShopCart obj = new ShopCart();
		BaseUser user = userUtils.getUser();

		obj.setShop(product.getShop());
		obj.setProduct(product);
		obj.setFlag(FlagEnum.valid);
		obj.setCreatedBy(user.getCreatedBy());
		obj.setNum(1);
		return super.add(form);

	}

	@Override
	public Map<String, SearchFilter> buildByForm(ShopCartForm form) {
		Map<String, SearchFilter> filters = buildFilter(form);

		if (form.getProductId() != null && form.getProductId() != 0) {
			filters.put("product.id", new SearchFilter("product.id", Operator.EQ,
					form.getProductId()));
		}
		return filters;
	}

	@Transactional
	@Override
	public ShopCart increment(ShopCart shopCart) {
		shopCart.setNum(shopCart.getNum() + 1);
		return super.edit(shopCart);
	}

	@Transactional
	@Override
	public ShopCart decrease(ShopCart shopCart) {
		shopCart.setNum(shopCart.getNum() - 1);
		return super.edit(shopCart);
	}
}
